/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.config.shard;

import br.com.model.entidade.Customer;
import org.hibernate.shards.ShardId;
import org.hibernate.shards.strategy.selection.ShardSelectionStrategy;

/**
 * Customized Shard Selection Strategy to return the Shard Id based on the
 * Tenant Id
 *
 * @author Arun Viswanathan
 */
public class CustomerShardSelectionStrategy implements ShardSelectionStrategy {

    public ShardId selectShardIdForNewObject(Object obj) {
        if (obj instanceof Customer) {
            return getShardId(((Customer) obj).getTenantId());
        }
        throw new IllegalArgumentException();
    }

    public ShardId getShardId(String tenantId) {
        int shardId = 0;

        if (tenantId.equalsIgnoreCase("tenant1") || tenantId.equalsIgnoreCase("tenant2")) {
            shardId = 0;
        } else if (tenantId.equalsIgnoreCase("tenant3")) {
            shardId = 1;
        } else if (tenantId.equalsIgnoreCase("tenant4")) {
            shardId = 2;
        } else if (tenantId.equalsIgnoreCase("tenant5")) {
            shardId = 3;
        }

        return new ShardId(shardId);
    }
}
